﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Lidgren.Network;
using Networking;

namespace GameNetworked_Server
{
    public class Program
    {
        private static Server Server;

        public static void Main(string[] args)
        {
            Server = new Server(7777, LogLevel.All);
            Server.Start();
            new Thread(new ThreadStart(delegate 
                {
                    while (true)
                    {
                        Server.NetUpdate();
                    }
                })).Start();
            Server.OnClientConnect += Server_OnClientConnect;
            Server.OnClientDisconnect += Server_OnClientDisconnect;
            Server.OnReceivePlayerSyncData += Server_OnReceivePlayerSyncData;
            Console.ReadKey();
        }

        static void Server_OnReceivePlayerSyncData(int playerkey, SyncDataType syncdatatype, NetIncomingMessage incmsg)
        {
            switch (syncdatatype)
            {
                case SyncDataType.Position:

                    float xPos = incmsg.ReadFloat();
                    Server.Players[playerkey].PosX += xPos;
                    NetOutgoingMessage outmsg = Server.BeginSendPlayerDataToAll(playerkey, SyncDataType.Position);
                    outmsg.Write(xPos);
                    Server.EndSendPlayerDataToAll(outmsg, Server.Players[playerkey].Connection);
                    break;
            }
        }

        static void Server_OnClientDisconnect(int playerkey, string reason, NetIncomingMessage incmsg)
        {
            Console.WriteLine("A client disconnected with key " + playerkey.ToString() + " for " + reason);
        }

        static void Server_OnClientConnect(int playerkey, NetIncomingMessage incmsg)
        {
            Console.WriteLine("A client connected with key " + playerkey.ToString());
        }
    }
}
